import urllib2
from getip import getip
import xml.etree.ElementTree as ET
import pickle
import sys

def readkey(key,port):
    url = "http://" + getip() + ":"+str(port)+"/lookup?key="+urllib2.quote(key)+"&wait=yes&destination="+getip()+":"+str(port)+""
    req = urllib2.Request(url)
    response = urllib2.urlopen(req)
    ans = response.read()
    xml = ET.fromstring(ans)
    key = None
    val = None
    for body in xml.findall('body'):
        for form in body.findall('form'):
            if form.attrib['name'] == 'request':
                for input in form.findall('input'):
                    if input.attrib['name'] == 'key':
                        key = input.attrib['value']
                    elif input.attrib['name'] == 'val':
                        val = input.attrib['value']
    val = pickle.loads(val)
    return val

def storekey(key,value,port):
    url = "http://" + getip() + ":"+str(port)+"/store?key="+urllib2.quote(key)+"&value="+urllib2.quote(value)
    req = urllib2.Request(url)
    response = urllib2.urlopen(req)
    ans = response.read()

if len(sys.argv)==1:
    print "usage: python fclient.py nhosts"
elif len(sys.argv)==2:
    n = int(sys.argv[1])
    for i in xrange(0,n):
        key = 'foo'+str(i)
        val = 'baz'+str(i)
        port = 4000+i
        storekey(key,val,port)
        print 'store',key,val,port
    for i in xrange(0,n):
        key = 'foo'+str(i)
        port = 4000+n-1-i
        val = readkey(key,port)
        print 'load',key,val,port
elif len(sys.argv)==3:
    n = int(sys.argv[1])
    i = int(sys.argv[2])
    key = 'foo'+str(i)
    val = 'baz'+str(i)
    port = 4000+i
    storekey(key,val,port)
    print 'store',key,val,port
    key = 'foo'+str(i)
    port = 4000+n-1-i
    val = readkey(key,port)
    print 'load',key,val,port
